<template>
	<el-upload ref="uploadRef" :action="uploadUrl" class="upload-peak" :data="params" :before-upload="beforeUpload" :disabled="disabled" :file-list="fileList" :headers="{ Authorization: getCurToken() }" :limit="limit" :multiple="false" :on-error="handleError" :on-remove="handleRemove" :on-success="handleSuccess" :size="size">
		<el-button class="upload-btn">
			<i class="iconfont icon-upload-pk" style="margin-right: 4px" />
			{{ title }}
		</el-button>
	</el-upload>
</template>
<script setup>
import global from '@/utils/global'
import { getToken } from '@/utils/storage'
/*
 *@Description: 状态初始化
 *@MethodAuthor: liuYuFeng
 *@Date: 2023-10-20 11:43:59
 */
const emit = defineEmits(['success', 'remove'])
const props = defineProps({
	url: {
		type: String,
		default: import.meta.env.VITE_API_URL + '/meta-system/web/v1/upload/uploadByBucketName',
	},
	title: {
		type: String,
		default: '上传附件',
	},
	size: {
		type: String,
		default: 'small',
	},
	limit: {
		type: Number,
		default: 1,
	},
	disabled: {
		type: Boolean,
		default: false,
	},
	params: {
		type: Object,
		default: function () {
			return {}
		},
	},
	list: {
		type: Array,
		default: () => [],
	},
	isValiDoc: {
		type: Boolean,
		default: false,
	},
})

const state = reactive({
	fileList: props.list,
	uploadUrl: props.url,
	uploadRef: null,
})

const { fileList, uploadUrl, uploadRef } = toRefs(state)

/*
 *@Description: 生命周期
 *@MethodAuthor: liuYuFeng
 *@Date: 2023-10-20 11:44:19
 */
watch(
	() => props.list,
	val => {
		state.fileList = val
	}
)
onMounted(() => {
	state.fileList = props.list
})
/*
 *@Description: 方法模块
 *@MethodAuthor: liuYuFeng
 *@Date: 2023-10-20 11:44:28
 */
const handleRemove = (file, uploadFiles) => {
	state.fileList = uploadFiles
	emit('remove', file, uploadFiles)
}
const handleSuccess = (response, uploadFile) => {
	if (response.code == 200) {
		emit('success', response.data)
	} else {
		global.$baseMessage(response.msg, 'error')
		state.uploadRef.handleRemove(uploadFile)
	}
}
const handleError = err => {
	console.log(err)
}
const handleResetValue = () => {
	state.fileList = []
}

const beforeUpload = file => {
	const isDoc = /\.(doc|docx)$/.test(file.name)
	if (!isDoc && props.isValiDoc) {
		global.$baseMessage('上传文件只能是 doc 或 docx 格式!', 'error')
		return false
	}
	return true
}

const getCurToken = () => {
	const tokenVal = getToken()
	if (tokenVal) {
		return `sop ${tokenVal}`
	} else {
		return ''
	}
}
defineExpose({
	handleResetValue,
})
</script>
<style lang="scss" scoped>
:deep() {
	.el-upload {
		width: 100px;
		.el-button {
			width: 100%;
		}
	}
}
</style>
